import {
	generateUUID
} from '@/utils/uuid';
import {
	getUserAuthProfile
} from '@/api/system/user';
import {
	getUserTokenInfo,
	removeUserTokenInfo,
	setToken,
	setUserTokenInfo
} from './auth';
import { callbackUrl, configDid } from '../config';
// #ifdef H5
function initUserPlugin() {
	// 这里根据移动端原生的 userAgent 来判断当前是 Android 还是 ios
	const u = navigator.userAgent
	// Android终端
	const isAndroid = u.startsWith("QzApp") && u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
	// IOS 终端
	const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)

	/**
	 * 配合 IOS 使用时的初始化方法
	 */
	const iosFunction = (callback) => {
		if (window.WebViewJavascriptBridge) {
			return callback(window.WebViewJavascriptBridge)
		}
		if (window.WVJBCallbacks) {
			return window.WVJBCallbacks.push(callback)
		}
		window.WVJBCallbacks = [callback]
		var WVJBIframe = document.createElement('iframe')
		WVJBIframe.style.display = 'none'
		WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__'
		document.documentElement.appendChild(WVJBIframe)
		setTimeout(function() {
			document.documentElement.removeChild(WVJBIframe)
		}, 0)
	}

	/**
	 * 配合 Android 使用时的初始化方法
	 */
	const androidFunction = (callback) => {
		if (window.WebViewJavascriptBridge) {
			callback(window.WebViewJavascriptBridge)
		} else {
			document.addEventListener('WebViewJavascriptBridgeReady', function() {
				callback(window.WebViewJavascriptBridge)
			}, false)
		}
	}
	window.setupWebViewJavascriptBridge = isAndroid ? androidFunction : isIOS ? iosFunction : androidFunction
	window.setupWebViewJavascriptBridge(function(bridge) {

	})
}
initUserPlugin()
// #endif
// js注册方法
export function appCallJsRegister(name, callBack) {
	window.setupWebViewJavascriptBridge(
		bridge => {
			bridge.registerHandler(name, callBack)
		}
	)
}

// js传递数据给java
export function jsToCallApp(data, callBack) {
	if (window.WebViewJavascriptBridge) {
		window.WebViewJavascriptBridge.callHandler(
			'h5CallApp',
			data,
			function(responseData) {
				// 回传的数据
				callBack && callBack(responseData)
			}
		)
	} else {
		callBack && callBack({
			code: 404,
			msg: '卡包环境不存在，获取授权失败',
		})
	}
}



// 调用 App 方法并处理回调
export const openAppFunction = (type, otherData, uuid, code, isRealAuth) => {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			if (isRealAuth) {
				jsToCallApp({
					type,
					...otherData
				}, (response) => {
					const expectedResponse = JSON.stringify({
						code: '0',
						msg: ''
					});
					const expectedResponseIos = JSON.stringify({
						code: '0',
						callType: 'toOpenKbAuthGetAuthInfo'
					});
					if (response === expectedResponse || response === expectedResponseIos) {
						resolve({
							code: 200,
							msg: '授权调用成功',
							uuid,
							backData: response,
							code,
						});
					} else {
						reject({
							code: 503,
							msg: '授权调用失败',
							backData: response,
							code,
						});
					}
				});
			} else {
				resolve({
					code: 200,
					uuid,
					code,
					msg: '测试授权成功',
				});
			}
		}, 300);
	});
};



// Base64 编码函数
const encodeBase64 = (str) => Buffer.from(str).toString('base64');

// 用户授权方法
const userAuth = async (isRealAuth, credentials) => {
	const uuid = generateUUID();
	const authPurpose = isRealAuth ? '入会转会' : '入会转会_测试';
	const url = `${callbackUrl}/organization/identity/notify/authorization`;
	const code = `DA2\\\\${configDid}\\\\${credentials}\\\\${uuid}\\\\${authPurpose}\\\\${encodeBase64(url)}`;

	return await openAppFunction('toOpenKbAuthGetAuthInfo', {
		authCode: code
	}, uuid, code, isRealAuth);
};

// 用户授权方法 - 扫码登陆
const sendCodeUserAuth = async (isRealAuth, credentials, uuid) => {
	const authPurpose = isRealAuth ? '扫码登陆' : '扫码登陆';
	const url = `${callbackUrl}/organization/identity/notify/sysAuthorization`;
	const code = `DA2\\\\${configDid}\\\\${credentials}\\\\${uuid}\\\\${authPurpose}\\\\${encodeBase64(url)}`;
	return await openAppFunction('toOpenKbAuthGetAuthInfo', {
		authCode: code
	}, uuid, code, isRealAuth);
};

/**
 * 授权过滤方法
 * @param {Object} str
 */

function parseFields(str) {
	return str.split('&').flatMap(item => {
		const match = item.match(/\((.*?)\)/);
		if (match) {
			const insideBrackets = match[1].split('|').map(part => part.trim());
			const outside = item.replace(/\(.*?\)/, '').trim();
			return [outside, ...insideBrackets].filter(Boolean); 
		}
		return [item.trim()].filter(Boolean); 
	});
}


// 用户顶级授权方法
export async function userTopAuth(isRealAuth, credentials) {

	try {
		const tokenInfo = getUserTokenInfo();
		const AuthData = parseFields(credentials)
		
		console.log(tokenInfo,"当前人信息");

		if (tokenInfo) {

			return tokenInfo;
		}
		// 调用用户授权并获取数据
		const userAuthData = await userAuth(isRealAuth, credentials);
		// 获取用户授权信息
		const profileData = await getUserAuthProfile(userAuthData.uuid || "test-uuid-test-uuid-test-uuid",
			isRealAuth);
		// 处理用户授权信息
		const userAuthInfo = processUserAuthInfo(profileData.data);
		setUserTokenInfo(userAuthInfo)
		return userAuthInfo
	} catch (error) {
		removeUserTokenInfo()
		throw error;
	}
}

// 用户顶级授权方法 - 扫码登陆
export async function sendCodeUserTopAuth(isRealAuth, credentials, uuid) {
	try {
		const userAuthData = await sendCodeUserAuth(isRealAuth, credentials, uuid);
		return userAuthData;
	} catch (error) {
		throw error;
	}
}

// 处理授权信息的辅助方法
function processUserAuthInfo(authData) {
	const authDataObj = {};
	const userDid = authData.did;
	const appToken = authData['App-Authorization'];  
	setToken(appToken);
	delete authData['App-Authorization'];  
	delete authData.did;
	delete authData['@type'];

	for (let key in authData) {
		if (authData.hasOwnProperty(key)) {
			try {
				const parsedContent = JSON.parse(authData[key]);
				authDataObj[key] = {
					...parsedContent.content,
					userDid: userDid,
				};
			} catch (error) {
				console.error(`${key}:`, error);
				authDataObj[key] = {
					content: null,
					userDid: userDid,
				};
			}
		}
	}

	return authDataObj;
}
